<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\exception\ConfigException;
use app\admin\model\SystemConfig;
use app\admin\validate\ConfigValidate;
use app\admin\validate\IDMustBePositiveInt;
use think\facade\View;
use think\Request;

class Config extends Base
{
    //
    public function index(){
        $config = SystemConfig::getAllConfig();
        View::assign([
            'lists' => $config->toArray()
        ]);
        return View::fetch();
    }
    public function add(Request $request)
    {
        //
        if($request->isPost()){
            (new ConfigValidate())->goCheck(ConfigValidate::Save);
            $params = $request->param();
            $res = SystemConfig::create($params,['name','content','type','value']);
            if($res->isEmpty()){
                throw new ConfigException([
                    'code' => 404,
                    'msg' => '添加配置失败',
                    'errorCode' => 10400
                ]);
            }
            return json([
                'msg' => '保存成功',
                'error_code' => 0
            ],200);

        }else{
            return View::fetch();
        }
    }
    public function edit(Request $request,$id)
    {
        //
        (new IDMustBePositiveInt)->goCheck('check');
        $config = SystemConfig::getConfigByID($id);
        if (!$config) {
            throw new ConfigException([
                'code' => 404,
                'msg' => '请传入配置ID',
                'errorCode' => 10402
            ]);
        }
        if ($request->isPost()){
            (new ConfigValidate())->goCheck(ConfigValidate::Update);
            $params = $request->param();

            $res = $config->save($params);
            if(!$res){
                throw new ConfigException([
                    'code' => 404,
                    'msg' => '修改配置失败',
                    'errorCode' => 10403
                ]);
            }
            return json([
                'msg' => '保存成功',
                'error_code' => 0
            ],200);

        }else{
            View::assign([
                'info' => $config->toArray()
            ]);
            return View::fetch();
        }
    }
    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        (new IDMustBePositiveInt())->goCheck('check');
        $config = SystemConfig::getConfigByID($id);
        if (!$config) {
            throw new ConfigException([
                'code' => 404,
                'msg' => '请传入配置ID',
                'errorCode' => 10402
            ]);
        }
        if(!$config->delete()){
            throw new ConfigException([
                'code' => 404,
                'msg' => '删除配置失败',
                'errorCode' => 10404
            ]);
        }
        return json([
            'msg' => '删除成功',
            'error_code' => 0
        ],200);
    }
}
